
import random
import openpyxl


# 数据导出
def init_student_data():
    """
    初始化学生数据
    """
    subject = ["Python", "Java", "C++", "数据结构", "人工智能"]
    stu = []
    for i in range(1000):
        courseName = subject[i % len(subject)]
        score = random.randint(0, 100)  # 生成0-100的随机整数
        obj = {"no": "A00" + str(i), "name": "学生" + str(i + 1), "course": courseName, "score": score}
        stu.append(obj)
    return stu


def export_data_to_excel(data, filename="student_scores.xlsx"):
    """
    将数据导出到Excel文件，确保标题占据一个单元格
    """
    try:
        # 创建一个新的工作簿
        wb = openpyxl.Workbook()
        ws = wb.active
        ws.title = "学生成绩数据"

        # 写入表头，每个标题占据一个单元格
        headers = ["学号", "姓名", "课程", "分数"]
        for col, header in enumerate(headers, 1):
            ws.cell(row=1, column=col).value = header

        # 写入数据
        for row, item in enumerate(data, 2):
            ws.cell(row=row, column=1).value = item["no"]
            ws.cell(row=row, column=2).value = item["name"]
            ws.cell(row=row, column=3).value = item["course"]
            ws.cell(row=row, column=4).value = item["score"]

        # 保存工作簿
        wb.save(filename)
        print(f"数据已成功导出到{filename}")

    except Exception as e:
        print(f"导出数据到Excel文件失败: {e}")


# 生成数据并导出到Excel
new_data = init_student_data()
export_data_to_excel(new_data)